from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth import password_validation
from django.core.exceptions import ValidationError
from django.contrib.auth import login
from django.utils import timezone
import random
import string
from .models import InviteCode
from .forms import UserRegisterForm
from django import forms
import time
import hashlib

@login_required
def profile(request):
    if request.method == 'POST':
        user = request.user
        # 获取表单数据
        nickname = request.POST.get('nickname', '').strip()
        phone_number = request.POST.get('phone_number', '').strip()
        real_name = request.POST.get('real_name', '').strip()
        
        # 验证必填项
        if not nickname:
            messages.error(request, '昵称不能为空')
            return render(request, 'user/profile.html')
            
        if not phone_number:
            messages.error(request, '手机号不能为空')
            return render(request, 'user/profile.html')
            
        # 验证手机号格式（简单验证）
        if not phone_number.isdigit() or len(phone_number) != 11:
            messages.error(request, '请输入正确的11位手机号')
            return render(request, 'user/profile.html')
        
        # 更新基本信息
        user.nickname = nickname
        user.real_name = real_name
        user.phone_number = phone_number
        
        # 处理密码修改
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        
        if old_password:
            if not user.check_password(old_password):
                messages.error(request, '原密码不正确')
                return render(request, 'user/profile.html')
            
            if new_password != confirm_password:
                messages.error(request, '两次输入的新密码不一致')
                return render(request, 'user/profile.html')
            
            if new_password:
                # 使用Django的密码验证器进行验证
                try:
                    password_validation.validate_password(new_password, user)
                except ValidationError as error:
                    messages.error(request, '\n'.join(error.messages))
                    return render(request, 'user/profile.html')
                
                user.set_password(new_password)
                update_session_auth_hash(request, user)  # 更新会话，避免用户被登出
        
        user.save()
        messages.success(request, '个人信息更新成功')
        return redirect('profile')
    
    return render(request, 'user/profile.html')

def generate_invite_code():
    """生成6位邀请码，使用时间戳和随机数混合生成"""
    chars = '34789acdefghjkpqrtwxy'
    timestamp = str(int(time.time() * 1000))  # 毫秒级时间戳
    random_str = ''.join(random.choice(chars) for _ in range(3))
    
    # 组合时间戳和随机字符
    source = f"{timestamp}{random_str}"
    
    # 使用MD5生成哈希
    hash_obj = hashlib.md5(source.encode())
    hash_hex = hash_obj.hexdigest()
    
    # 从哈希值中提取6个字符位置
    result = ''
    for i in range(6):
        # 使用哈希值的每3个字符生成一个索引
        index = int(hash_hex[i*3:i*3+3], 16) % len(chars)
        result += chars[index]
    
    return result

def generate_invite_codes(user, count=10):
    """为用户生成指定数量的邀请码"""
    codes = []
    max_attempts = 50  # 最大重试次数
    
    for _ in range(count):
        attempts = 0
        while attempts < max_attempts:
            code = generate_invite_code()
            if not InviteCode.objects.filter(code=code).exists():
                codes.append(InviteCode(code=code, creator=user))
                break
            attempts += 1
        else:
            raise Exception(f"无法生成唯一的邀请码，已尝试{max_attempts}次")
    
    InviteCode.objects.bulk_create(codes)

def register(request):
    initial = {}
    show_invite_code = True  # 默认显示邀请码输入框
    
    # 从 URL 参数获取邀请码
    if invite_code := request.GET.get('invite_code'):
        # 验证邀请码是否有效
        if not InviteCode.objects.filter(code=invite_code, used_by__isnull=True).exists():
            invite_code = None
            messages.error(request, '无效的邀请码，请重新输入')
    
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            invite_code = form.cleaned_data['invite_code']
            invite_code.used_by = user
            invite_code.used_at = timezone.now()
            invite_code.save()
            generate_invite_codes(user)
            login(request, user)
            messages.success(request, '注册成功！')
            return redirect('post_list')
        else:
            show_invite_code = True
    else:
        form = UserRegisterForm(initial=initial)
    
    return render(request, 'user/register.html', {
        'form': form,
        'invite_code': invite_code,
    })

def invite_codes(request):
    """查看邀请码页面"""
    if not request.user.is_authenticated:
        return redirect('login')
    
    available_codes = InviteCode.objects.filter(
        creator=request.user,
        used_by__isnull=True
    ).order_by('-created_at')
    
    used_codes = InviteCode.objects.filter(
        creator=request.user,
        used_by__isnull=False
    ).order_by('-used_at')
    
    return render(request, 'user/invite_codes.html', {
        'available_codes': available_codes,
        'used_codes': used_codes
    })
